import json
import os


def save_result_to_json(results: list, filename: str = "doubao_result.json"):
    try:
        # 如果文件存在，读取旧数据，否则初始化为空列表
        if os.path.exists(filename):
            with open(filename, "r", encoding="utf-8") as f:
                try:
                    data = json.load(f)
                    if not isinstance(data, list):
                        print("❌ 文件格式不正确，应为 JSON 数组。")
                        return
                except json.JSONDecodeError:
                    print("⚠️ 文件内容无法解析为 JSON，将重新初始化。")
                    data = []
        else:
            data = []

        # 逐个处理新结果，避免重复
        added_count = 0
        for result in results:
            # if '如图所示' in result.get('subject'):
            #     continue
            new_result_str = json.dumps(result, ensure_ascii=False, sort_keys=True)
            if any(json.dumps(item, ensure_ascii=False, sort_keys=True) == new_result_str for item in data):
                print("⚠️ 某条结果已存在，跳过。")
                continue
            data.append(result)
            added_count += 1

        if added_count == 0:
            print("⚠️ 没有新内容被写入。")
            return

        # 写入 JSON 文件
        with open(filename, "w", encoding="utf-8") as f:
            json.dump(data, f, ensure_ascii=False, indent=2)

        print(f"✅ 共追加 {added_count} 条记录到 {filename}")
    except Exception as e:
        print(f"❌ 写入 JSON 文件失败：{e}")
